﻿using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel;

namespace RoboSensors.Tools
{
    //public class JsonHelper
    //{
    //    public static Object Json2List(string jsonName, Type inputType)
    //    {
    //        JavaScriptSerializer sr = new JavaScriptSerializer();
    //        return sr.Deserialize(jsonName, inputType); //filters为json字符串
    //    }

    //}

    public static class JsonHelper
    {
        private static readonly JsonSerializerSettings srJsonSettings;

        static JsonHelper()
        {
            IsoDateTimeConverter datetimeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };

            srJsonSettings = new JsonSerializerSettings
            {
                MissingMemberHandling = MissingMemberHandling.Ignore,
                NullValueHandling = NullValueHandling.Ignore,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };
            srJsonSettings.Converters.Add(datetimeConverter);
        }

        /// <summary>
        /// 将指定的对象序列化成 JSON 数据。
        /// </summary>
        /// <param name="obj">要序列化的对象。</param>
        /// <returns></returns>
        public static string ToJson(this object obj)
        {
            try
            {
                if (null == obj)
                    return null;

                return JsonConvert.SerializeObject(obj, Formatting.Indented, srJsonSettings);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 将指定的 JSON 数据反序列化成指定对象。
        /// </summary>
        /// <typeparam name="T">对象类型。</typeparam>
        /// <param name="json">JSON 数据。</param>
        /// <returns></returns>
        public static T FromJson<T>(this string json) where T : class, new()
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(json, srJsonSettings);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static T JsonToModel<T, TChild>(this string json)
            where T : class, new()
            where TChild : class, new()
        {
            try
            {

                return JsonConvert.DeserializeObject<T>(json, new JsonCreationConverter<TChild>());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static T JsonToModel1<T, TChild>(this string json)
            where T : class, new()
        {
            try
            {

                return JsonConvert.DeserializeObject<T>(json, new JsonView2DTypeConvert<TChild>());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

    public class JsonCreationConverter<T> : JsonConverter where T : class, new()
    {
        protected T Create(Type t, JObject jsonObject)
        {
            if (jsonObject["Type"] == null)
            {
                throw new Exception("未找到Type的属性字段");
            }
            var typeName = jsonObject["Type"].ToString();
            var indexof = typeName.LastIndexOf('.');
            var libname = typeName.Substring(0, indexof);
            var clsName = typeName.Substring(indexof + 1);
            var model = ReflectionHelper.CreateInstance(libname, clsName);
            //var type = Type.GetType(typeName);
            //if (type != null) return type.Assembly.CreateInstance(typeName) as T;
            return model as T;
        }

        public override bool CanConvert(Type objectType)
        {
            return typeof(T).IsAssignableFrom(objectType);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jsonObject = JObject.Load(reader);
            var target = Create(objectType, jsonObject);
            serializer.Populate(jsonObject.CreateReader(), target);
            return target;
        }
    }

    public class JsonView2DTypeConvert<T> : JsonConverter
    {
        #region Overrides of JsonConverter

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jsonObject = JObject.Load(reader);
            object target = null;
            JToken temp;
            if (jsonObject.TryGetValue("Type", out temp))
            {
                target = ReflectionHelper.CreateInstance("View2DMethod", "Model." + Convert.ToInt64(temp.ToString()).ToEnum<PathType>());
            }
            serializer.Populate(jsonObject.CreateReader(), target);
            return target;
        }

        public override bool CanConvert(Type objectType)
        {
            return typeof(T).IsAssignableFrom(objectType);
        }

        #endregion
        public enum PathType
        {
            [Description("空")]
            None = -1, //空
            [Description("点")]
            View2DPoint = 0, //点
            [Description("线段")]
            View2DLine = 1, //线段
            [Description("圆弧")]
            View2DArc = 2, //圆弧
            [Description("圆")]
            View2DCircle = 3, //圆
            [Description("样条")]
            View2DSpLine = 4, //样条
            [Description("椭圆弧")]
            View2DEllipseArc = 5, //椭圆弧
            [Description("多段线")]
            View2DmulLines = 6, //多段线
            [Description("组合图元")]
            CombinedPath = 7 //组合图元
        }
    }

}